package com.nineclock.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.entity.UserInfo;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.system.dto.SysChangeMainManagerDTO;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.dto.SysRegisterDTO;
import com.nineclock.system.easyexcel.ExcelMember;
import com.nineclock.system.easyexcel.MemberParseListener;
import com.nineclock.system.mapper.*;
import com.nineclock.system.pojo.*;
import com.nineclock.system.service.OrganizationService;
import com.nineclock.system.service.SMSService;
import com.nineclock.system.service.SysCompanyUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class SysCompanyUserServiceImpl implements SysCompanyUserService {
    @Autowired
    SysCompanyUserMapper sysCompanyUserMapper;
    @Override
    public SysCompanyUserDTO queryCompanyManagerInfo() {
        UserInfo userInfo = CurrentUserHolder.get();
        Long companyId = userInfo.getCompanyId();
        SysCompanyUser sysCompanyUser = sysCompanyUserMapper.queryCompanyManagerInfo(companyId);
        if (sysCompanyUser == null) {
            throw new NcException(ResponseEnum.COMPANY_ADMIN_NOT_EXISTS);
        }
        return BeanHelper.copyProperties(sysCompanyUser, SysCompanyUserDTO.class);

    }
    @Autowired
    SysUserMapper sysUserMapper;
    //手机号是否存在
    @Override
    public Boolean checkExists(String mobile) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getMobile,mobile);
        Integer i = sysUserMapper.selectCount(queryWrapper);
        return i==1;
    }
    //获取员工列表
    @Override
    public List<SysCompanyUserDTO> getCompanyUserList() {
        UserInfo userInfo = CurrentUserHolder.get();
        Long companyId = userInfo.getCompanyId();
        LambdaQueryWrapper<SysCompanyUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysCompanyUser::getCompanyId,companyId);
        queryWrapper.eq(SysCompanyUser::getEnable,1);
        List<SysCompanyUser> sysCompanyUsers = sysCompanyUserMapper.selectList(queryWrapper);
        if(CollectionUtil.isEmpty(sysCompanyUsers)){
            throw new NcException(ResponseEnum.USER_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(sysCompanyUsers,SysCompanyUserDTO.class) ;
    }
    @Autowired
    SysCompanyUserRoleMapper sysCompanyUserRoleMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    SMSService smsService;
    @Autowired
    SysRoleMapper sysRoleMapper;
    @Override
    public void exchangeManager(SysChangeMainManagerDTO sysChangeMainManagerDTO) {
        if(sysChangeMainManagerDTO == null || sysChangeMainManagerDTO.getCode() == null || sysChangeMainManagerDTO.getUserId() == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //获取预备管理员信息
        SysCompanyUser sysCompanyUser = sysCompanyUserMapper.selectById(sysChangeMainManagerDTO.getUserId());
        if (sysCompanyUser==null) {
            throw new NcException(ResponseEnum.USER_NOT_FOUND);
        }
        Boolean aBoolean = smsService.checkCode(sysChangeMainManagerDTO.getCode(), sysCompanyUser.getMobile(), SMSConstant.SMS_TYPE_CHANGE_MANAGER);
        if (!aBoolean) {
            throw new NcException(ResponseEnum.CODE_IMAGE_ERROR);
        }
        UserInfo userInfo = CurrentUserHolder.get();
        Long companyId = userInfo.getCompanyId();
        LambdaQueryWrapper<SysRole> s = new LambdaQueryWrapper<>();
        s.eq(SysRole::getRoleName,"ROLE_ADMIN_SYS");
        s.eq(SysRole::getCompanyId,companyId);
        SysRole sysRole = sysRoleMapper.selectOne(s);
        Long mi = sysRole.getId();
        sysCompanyUserRoleMapper.deleteManager(companyId,mi);
        sysCompanyUserRoleMapper.insertManager(sysChangeMainManagerDTO.getUserId(),companyId,mi);
    }


    @Override
    public Integer addUser(SysRegisterDTO sysRegisterDTO) {
        Boolean aBoolean = smsService.checkCode(sysRegisterDTO.getCheckcode(), sysRegisterDTO.getMobile(), SMSConstant.SMS_TYPE_REGISTER);
        if (!aBoolean) {
            throw new NcException(ResponseEnum.CODE_IMAGE_ERROR);
        }
        SysUser sysUser = new SysUser();
        //密码
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(sysRegisterDTO.getPassword());
        //设定数值
        sysUser.setPassword(encode);
        sysUser.setCreateTime(new Date());
        sysUser.setMobile(sysRegisterDTO.getMobile());
        sysUser.setStatus((short)1);

        sysUserMapper.insert(sysUser);
        return (int)(long)sysUser.getId();
    }

    @Override
    public void parseExcel(MultipartFile excelFile) throws IOException {
        EasyExcel.read(excelFile.getInputStream(),ExcelMember.class,new MemberParseListener(this))
                .sheet(0)
                .doRead();
    }
    @Autowired
    SysDepartmentMapper sysDepartmentMapper;

    @Override
    public void importData(List<ExcelMember> data) {
        if( data != null){
            for (ExcelMember member : data) {
                //判断 手机号和邮箱 是否已存在
                LambdaQueryWrapper<SysUser> userQw = new LambdaQueryWrapper<>();
                userQw.eq(SysUser::getMobile, member.getMobile())
                        .or()
                        .eq(SysUser::getEmail, member.getEmail());
                Integer count = sysUserMapper.selectCount(userQw);
                if(count > 0){
                    throw new NcException(ResponseEnum.USER_MOBILE_EMAIL_EXISTS);
                }

                //判断工号是否重复
                LambdaQueryWrapper<SysCompanyUser> companyUserQw = new LambdaQueryWrapper<>();
                companyUserQw.eq(SysCompanyUser::getCompanyId, CurrentUserHolder.get().getCompanyId());
                companyUserQw.eq(SysCompanyUser::getWorkNumber, member.getWorkNumber());

                Integer count1 = sysCompanyUserMapper.selectCount(companyUserQw);
                if(count1 > 0){
                    throw new NcException(ResponseEnum.WROK_NUM_EXISTS);
                }


                //新增用户
                SysUser user = new SysUser();
                user.setUsername(member.getName());
                user.setEmail(member.getEmail());
                user.setMobile(member.getMobile());
                //初始密码
                user.setPassword(new BCryptPasswordEncoder().encode("123456"));
                user.setCreateTime(new Date());
                user.setStatus((short)1);
                user.setLastLoginCompanyId(CurrentUserHolder.get().getCompanyId());

                sysUserMapper.insert(user);

                //新增员工
                SysCompanyUser companyUser = new SysCompanyUser();
                companyUser.setUserName(member.getName());
                companyUser.setMobile(member.getMobile());
                companyUser.setEmail(member.getEmail());
                companyUser.setCompanyId(CurrentUserHolder.get().getCompanyId());
                companyUser.setCompanyName(CurrentUserHolder.get().getCompanyName());
                companyUser.setEnable((short)1);
                companyUser.setRemark(member.getDesc());
                companyUser.setCreateTime(new Date());
                companyUser.setTimeEntry(member.getEntryTime());
                companyUser.setPost(member.getPosition());
                companyUser.setOfficeAddress(member.getWorkAddr());
                companyUser.setUserId(user.getId());
                companyUser.setWorkNumber(member.getWorkNumber());

                //根据部门名称 查询部门对象
                LambdaQueryWrapper<SysDepartment> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(SysDepartment::getCompanyId, CurrentUserHolder.get().getCompanyId());
                wrapper.eq(SysDepartment::getName, member.getDepartmentName());
                SysDepartment department = sysDepartmentMapper.selectOne(wrapper);

                if(department != null){
                    //设置部门信息
                    companyUser.setDepartmentId(department.getId());
                    companyUser.setDepartmentName(department.getName());
                }
                sysCompanyUserMapper.insert(companyUser);

                //维护员工和角色的关系
                LambdaQueryWrapper<SysRole> roleQw = new LambdaQueryWrapper<>();
                roleQw.eq(SysRole::getCompanyId, CurrentUserHolder.get().getCompanyId());
                roleQw.eq(SysRole::getRoleDesc, member.getRoleName());

                SysRole role = sysRoleMapper.selectOne(roleQw);
                if(role != null){
                    SysCompanyUserRole companyUserRole = new SysCompanyUserRole();
                    companyUserRole.setCompanyUserId(companyUser.getId());
                    companyUserRole.setCompanyId(CurrentUserHolder.get().getCompanyId());
                    companyUserRole.setRoleId(role.getId());

                    sysCompanyUserRoleMapper.insert(companyUserRole);
                }
            }
        }
    }
    @Autowired
    OrganizationServiceImpl organizationService;
    @Override
    public Integer queryUserCountByDepartmentIds(List<Long> departmentIds) {
        if (CollectionUtil.isEmpty(departmentIds)) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        List<Long> longs = new ArrayList<>();
        longs.addAll(departmentIds);
        for (Long departmentId : departmentIds) {
            organizationService.getAllDownDepartmentList(departmentId,CurrentUserHolder.get().getCompanyId()
            ,longs);
        }
        LambdaQueryWrapper<SysCompanyUser> companyUserWrapper = new LambdaQueryWrapper<>();
        companyUserWrapper.in(SysCompanyUser::getDepartmentId,longs);
        companyUserWrapper.eq(SysCompanyUser::getCompanyId,CurrentUserHolder.get().getCompanyId());
        companyUserWrapper.eq(SysCompanyUser::getEnable,1);
        return sysCompanyUserMapper.selectCount(companyUserWrapper);
    }
}
